﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using SmartSpace;
using System.IO;
using SmartSpace.Packaging;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class user_list : System.Web.UI.Page
    {
        private Guid _selectedUserId;

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                _selectedUserId = new Guid(Request.QueryString["id"]);
            }

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                PagedList<User> users = service.GetUsers(0, 999);
                _ctlListUser.DataSource = users;
                _ctlListUser.DataBind();
            }
        }

        protected void _ctlBtnDelete_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            foreach (Control itemContainer in _ctlListUser.Controls)
            {
                CheckBox checkBox = itemContainer.FindControl("_ctlCheckId") as CheckBox;

                if (checkBox != null && checkBox.Checked)
                {
                    HiddenField hiddenField = (HiddenField)itemContainer.FindControl("_ctlHiddenId");
                    Guid userId = new Guid(hiddenField.Value);
                    service.DeleteUser(userId);
                }
            }

            Response.Redirect(Request.Url.AbsoluteUri);
        }

        protected void _ctlBtnResetPassword_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            foreach (Control itemContainer in _ctlListUser.Controls)
            {
                CheckBox checkBox = itemContainer.FindControl("_ctlCheckId") as CheckBox;

                if (checkBox != null && checkBox.Checked)
                {
                    HiddenField hiddenField = (HiddenField)itemContainer.FindControl("_ctlHiddenId");
                    Guid userId = new Guid(hiddenField.Value);
                    User user = service.GetUser(userId);
                    user.Password = SmartSpace.Core.User.EncryptMD5("pwd123456");
                    service.SaveUser(user);
                }
            }

            Response.Redirect(Request.Url.AbsoluteUri);
        }
    }
}